<%@ page pageEncoding="utf-8"%>
<%@include file="/views/common/common.jsp"%>
<script type="text/javascript">
//websocket对象
var ws = null;

//初始化方法
$(document).ready(function() {
	//初始化websocket
	if(!window.WebSocket){
        alertMessager('您的浏览器不支持WebSocket');
	}else{
		init_socket();
	}
	//初始化MyTab事件
	init_mytab();
});

/**
 * 初始化MyTab事件
 */
function init_mytab(){
	//监听右键事件，创建右键菜单
    $('#myTab').tabs({
        onContextMenu:function(e, title,index){
            e.preventDefault();
            if(index>=0){
                $('#my_tab_menu').menu('show', {
                    left: e.pageX,
                    top: e.pageY
                }).data("tabTitle", title);
            }
        }
    });
	
	
    //右键菜单点击事件
    $("#my_tab_menu").menu({
        onClick:function (item) {
        	//刷新当前页面
        	if(item.name=='tab_refresh'){
        		var tab=$('#myTab').tabs('getSelected');
        		var tabindex = $('#myTab').tabs('getTabIndex',tab);
        		if(tabindex>0){
        			tab.find('iframe')[0].contentWindow.location.reload(true);
        		}else{
        			//刷新主页
        			$('#index_iframe').attr('src', $('#index_iframe').attr('src'));
        		}
        	}
        	//关闭其它
			if(item.name=='tab_close_other_all'){
				var tablist=$('#myTab').tabs('tabs');
				var tab=$('#myTab').tabs('getSelected');
				for(var i=tablist.length-1;i>0;i--){
				    if(tab!=tablist[i]){
				       $('#myTab').tabs('close',i);
				    }
				 }
        	}
        	//关闭全部
			if(item.name=='tab_close_all'){
				var tablist=$('#myTab').tabs('tabs');
			    for(var i=tablist.length-1;i>0;i--){
			         $('#myTab').tabs('close',i);    
			    }   
			}
        }
    });
}

//发送用户上线通知
function SendUserOnLine(){
	var userid = '${zuser.zid}';
	var username = '${zuser.user_name}';
	//创建JSON对象
	var msgObj = {
		fromuserid : userid,
		fromusername: username,
		command_type:'user_on_line'
	};
	
	//发送消息
	ws.send(JSON.stringify(msgObj));
}

function init_socket(){
	var isMSN = '${sp.isMSN}';
	
	if(isMSN=='true'){
		var serverip = '${sp.serverip}';
		var isSSL = '${sp.isSSL}';
		
		var HTTPHEAD = 'ws';
		if(isSSL=='true'){
			HTTPHEAD = "wss";
		}
		var socket_server_url = HTTPHEAD+'://'+serverip+'/zsocket'
		
		ws = new WebSocket(socket_server_url);
		
		//链接成功事件
		ws.onopen = function () {
			//alert("OK");
		}
		
		//接收到信息
		ws.onmessage = function (obj) {
			var ms = $.parseJSON(obj.data);
			if('usertouser' == ms.data.command_type){
				//显示消息
				printMsg(obj.data);
			}else if('user_on_line' == ms.data.command_type){
				var userid = '${zuser.zid}';
				var fromuserid = ms.data.fromuserid;
				var fromusername = ms.data.fromusername;
				if(userid!=fromuserid){
					RefreshMessagesList();
				}
			}else if('user_off_line' == ms.data.command_type){
				var userid = '${zuser.zid}';
				var fromuserid = ms.data.fromuserid;
				var fromusername = ms.data.fromusername;
				if(userid!=fromuserid){
					RefreshMessagesList();
				}
			}else if('system_message' == ms.data.command_type){
				alert(ms);
				
			}else if('group_message' == ms.data.command_type){
				
			}else if('e_message'==ms.data.command_type){
				var e_msg = ms.data.msg;
				alertErrorMessager(e_msg);
			}
		};
		// 关闭页面时候关闭ws
		window.addEventListener("beforeunload", function(event) {
		    ws.close();
		});
		
		ws.addEventListener('open', function () {
			//发送用户上线通知
			SendUserOnLine();
	    });
		
		if(isNull(ws.onopen)){
			//未成功链接WebSocket就关闭即时通讯列表
			$('#zmain_easyui_layout').layout('remove','east');
		}else{
			
		}
	}else{
		//未启用即时通讯关闭即时通讯列表
		$('#zmain_easyui_layout').layout('remove','east');
	}
}


/**
 * 刷新消息列表
 */
function RefreshMessagesList(){
	var session_userid = '${zuser.zid}';
	$.ajax({
	    type : "GET",
	    url : 'GetUserMessageList?touserid='+session_userid,
	    success : function(data) {
	        if(data.code=='SUCCESS'){
	        	$('#UserMessagesList').empty();
	        	var messages_length = data.data.length;
	        	for (var i = 0; i < messages_length; i++) {
	        		var messageinfo = data.data[i];
	        		var userid = messageinfo.zid;
	        		if(session_userid!=userid){
	        			var username = messageinfo.user_name;
		        		if(messageinfo.messagecount>0){
		        			username = username + '['+messageinfo.messagecount+']';
		        		}
		        		var buttoncss = 'btn btn-light btn-block';
		        		if(messageinfo.isonline==0){
		        			buttoncss = 'btn btn-success btn-block';
		        		}
						var button_html = '<button id="message_user_'+userid+'" type="button" class="'+buttoncss+'" onclick="OpenMessageWindows(\''+userid+'\',\''+messageinfo.user_name+'\')">'+username+'</button>';
		        		$('#UserMessagesList').append(button_html);
	        		}
				}
				
	        }
	    }
	});
}


/**
 * 显示消息
 */
function printMsg(r_text){
	if(isNotNull(r_text)){
		var r = $.parseJSON(r_text);
		var userid = '${zuser.zid}';
		var fromuserid = r.data.fromuserid;
		var fromusername = decodeURIComponent(r.data.fromusername);
		var touserid = r.data.touserid;
		var tousername = decodeURIComponent(r.data.tousername);
		var command_type = r.data.command_type;
		var msgtype = r.data.msgtype;
		var msg = decodeURIComponent(r.data.msg);
		var sendtime = r.data.sendtime;
		
		
		//保存聊天记录到Cookie
		var message_cookieid = 'message_cookieid_'+fromuserid+'_'+touserid;
		var message_cookie_obj = {
				fromuserid : fromuserid,
				fromusername: fromusername,
				touserid:touserid,
				tousername:tousername,
				sendtime:sendtime,
				msg:msg
		};
		var old_message_cookie = getCookie(message_cookieid);
		var new_message_cookie = old_message_cookie + '☆'+JSON.stringify(message_cookie_obj);
		setCookie(message_cookieid,new_message_cookie);
		
		
		//判读聊天窗口是否打开
		var isopen = $('#message_windows').parent().css('display');
		if(isopen=='none'){
			//未打开
			
			//发送右下角消息提醒
			if(userid==touserid){
				var msgHTML = '		<div class="msgbox">';
				 msgHTML = msgHTML + '			<div class="msgboxhead1">'+fromusername+' '+sendtime+'</div>';
				 msgHTML = msgHTML + '			<div class="msgboxtext">'+msg+'</div>';
				 msgHTML = msgHTML + '		</div>';
				alertMessager('<a href="javascript:void(0);" onclick="OpenMessageWindows(\''+fromuserid+'\',\''+fromusername+'\')">'+msgHTML+'</a>');
			}
			
			//更新用户头像后面消息数量
			UpdateMessageCount(fromuserid);
			
		}
		
		
		
		
		//将消息显示在对应 用户消息框中
		if(userid==fromuserid){
			//创建消息
			 var msgHTML = '		<div class="msgbox">';
			 msgHTML = msgHTML + '			<div class="msgboxhead1">'+fromusername+' '+sendtime+'</div>';
			 msgHTML = msgHTML + '			<div class="msgboxtext">'+msg+'</div>';
			 msgHTML = msgHTML + '		</div>';
			$('#msgboxlist_'+touserid).append(msgHTML);
			
			//控制滚动条到最底部
			var scrollHeight = $('#msgboxlist_'+touserid).prop("scrollHeight");
			$('#msgboxlist_'+touserid).animate({scrollTop:scrollHeight}, 400);
		}else{
			
			//判读是否已经建立了发信人消息框
			if (!$('#MessageTab').tabs('exists', fromusername)) {
				 var tabHTML = '<div class="easyui-layout" data-options="fit:true">';
				 tabHTML = tabHTML + '	<div id="msgboxlist_'+fromuserid+'" data-options="region:\'center\'" style="padding:10px;">';
				 tabHTML = tabHTML + '	</div>';
				 tabHTML = tabHTML + '	<div data-options="region:\'south\',split:true" style="position:relative;margin: 0px;padding: 0px;height: 150px;">';
				 tabHTML = tabHTML + '		<textarea id="msg_'+fromuserid+'" style="width: 100%;height: 100%;resize:none;border:none;"></textarea>';
				 tabHTML = tabHTML + '		<button class="btn btn-light" onclick="CloseMessageWindows(\''+fromuserid+'\',\''+fromusername+'\')" style="position:absolute;right:100px;bottom:5px;"><i class="fa fa-close"></i> 关闭</button>';
				 tabHTML = tabHTML + '		<button class="btn btn-light" onclick="sendMessage()" style="position:absolute;right:20px;bottom:5px;"><i class="fa fa-volume-up"></i> 发送</button>';
				 tabHTML = tabHTML + '	</div>';
				 tabHTML = tabHTML + '</div>';
				 
			     $('#MessageTab').tabs('add', {
			       title: fromusername,
			       id:fromuserid,
			       content: tabHTML
			     });
			     
			     //$('#MessageTab').tabs('select', fromusername);
			 } else {
				 var tab = $('#MessageTab').tabs('getSelected');
				 var title =tab.panel('options').title;
				 if(fromusername!=title){
					//更新用户头像后面消息数量
					UpdateMessageCount(fromuserid);
				 }
			 }
			
			//创建消息
			 var msgHTML = '		<div class="msgbox">';
			 msgHTML = msgHTML + '			<div class="msgboxhead0">'+fromusername+' '+sendtime+'</div>';
			 msgHTML = msgHTML + '			<div class="msgboxtext">'+msg+'</div>';
			 msgHTML = msgHTML + '		</div>';
			$('#msgboxlist_'+fromuserid).append(msgHTML);
			
			//控制滚动条到最底部
			var scrollHeight = $('#msgboxlist_'+fromuserid).prop("scrollHeight");
			$('#msgboxlist_'+fromuserid).animate({scrollTop:scrollHeight}, 400);
		}
	}
}


//更新用户头像后面消息数量
function UpdateMessageCount(fromuserid){
	$.ajax({
	    type : "GET",
	    async:true, //true为异步方法 false为同步方法
	    url : 'getFromuserMessageCount?fromuserid='+fromuserid,
	    success : function(data) {
	        if(data.code=='SUCCESS'){
				$('#message_user_'+fromuserid).text(data.data);
	        }
	    },
	    error: function (data) {
	        parent.alertErrorMessager('ajax错误：'+data);
	    }
	});
}

/**
 * 用户发送信息
 */
function sendMessage(){
	var fromuserid = '${zuser.zid}';
	var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
	var msg = encodeURIComponent($('#msg_'+touserid).val());
	var msgtype = '0';//0是文本消息

	//创建JSON对象
	var msgObj = {
			fromuserid : fromuserid,
			touserid : touserid,
			command_type:'usertouser',
			msgtype : msgtype,
			msg : msg
	};
	
	//发送消息
	ws.send(JSON.stringify(msgObj));
	
	
	//保存已发送消息到cookie
	var message_cookieid = 'message_cookieid_'+touserid+'_'+fromuserid;
	var fromusername = '${zuser.user_name}';
	var sendtime = getDateTime();
	var message_cookie_obj = {
			fromuserid : fromuserid,
			fromusername: fromusername,
			touserid:touserid,
			sendtime:sendtime,
			msg:msg
	};
	var old_message_cookie = getCookie(message_cookieid);
	var new_message_cookie = old_message_cookie + '☆'+JSON.stringify(message_cookie_obj);
	setCookie(message_cookieid,new_message_cookie);
	
	
	//请空已发送信息
	$('#msg_'+touserid).val('');
	$('#msg_'+touserid).focus();
	
}

function getDateTime(){
	var myDate = new Date();
	var year = myDate.getFullYear(); //获取当前年
    var mon = myDate.getMonth() + 1; //获取当前月
    var date = myDate.getDate(); //获取当前日
    var h = myDate.getHours();//获取当前小时数(0-23)
    var m = myDate.getMinutes();//获取当前分钟数(0-59)
    var s = myDate.getSeconds();//获取当前秒
    return year + "-" + mon + "-" + date + " " + h+":"+m+":" +s;
}

/**
 * 打开聊天窗口
 */
function OpenMessageWindows(fromuserid,fromusername){
	$('#fromuserid').val('${zuser.zid}');
	$('#touserid').val(fromuserid);
	
	if (!$('#MessageTab').tabs('exists', fromusername)) {
		 var tabHTML = '<div class="easyui-layout" data-options="fit:true">';
		 tabHTML = tabHTML + '	<div id="msgboxlist_'+fromuserid+'" data-options="region:\'center\'" style="padding:10px;">';
		 tabHTML = tabHTML + '	</div>';
		 tabHTML = tabHTML + '	<div data-options="region:\'south\',split:true" style="position:relative;margin: 0px;padding: 0px;height: 150px;">';
		 tabHTML = tabHTML + '		<textarea id="msg_'+fromuserid+'" style="width: 100%;height: 80%;resize:none;border:none;outline:none;margin-top:0px;margin-bottom:0px;"></textarea>';
		 tabHTML = tabHTML + '		<button class="btn btn-light" onclick="CloseMessageWindows(\''+fromuserid+'\',\''+fromusername+'\')" style="position:absolute;right:100px;bottom:5px;"><i class="fa fa-close"></i> 关闭</button>';
		 tabHTML = tabHTML + '		<button class="btn btn-light" onclick="sendMessage()" style="position:absolute;right:20px;bottom:5px;"><i class="fa fa-volume-up"></i> 发送</button>';
		 tabHTML = tabHTML + '	</div>';
		 tabHTML = tabHTML + '</div>';
		 
	     $('#MessageTab').tabs('add', {
	       title: fromusername,
	       id:fromuserid,
	       content: tabHTML
	     });
	 } else {
	     $('#MessageTab').tabs('select', fromusername);
	 }
	
	//设置焦点
	$('#msg_'+fromuserid).focus();
	
	//修改消息是否查看状态为以查看
	UpdateIsOpen(fromuserid,fromusername);
	
	
	//判读指定用户聊天窗口是首着次打开，如果是首次打开，加载cookie中的历史信息到当前窗口
	var touserid = '${zuser.zid}';
	var message_cookieid = 'message_cookieid_'+fromuserid+'_'+touserid;
	if($('#msgboxlist_'+fromuserid).children().length == 0){
		var old_message_cookie = getCookie(message_cookieid);
		var messageArray = old_message_cookie.split('☆');
		for (var i = 0; i < messageArray.length; i++) {
			var message_r_text = messageArray[i];
			if(isNotNull(message_r_text)){
				var r = $.parseJSON(message_r_text);
				var fromusername = r.fromusername;
				var msg = r.msg;
				var sendtime = r.sendtime;
				if(isNotNull(fromusername)){
					//创建消息
					 var msgHTML = '		<div class="msgbox">';
					 if(touserid==r.fromuserid){
						 msgHTML = msgHTML + '			<div class="msgboxhead1">'+fromusername+' '+sendtime+'</div>';
					 }else{
						 msgHTML = msgHTML + '			<div class="msgboxhead0">'+fromusername+' '+sendtime+'</div>';
					 }
					 
					 msgHTML = msgHTML + '			<div class="msgboxtext">'+msg+'</div>';
					 msgHTML = msgHTML + '		</div>';
					$('#msgboxlist_'+fromuserid).append(msgHTML);
				}
				
			}
			
		}
	}
	
	//直接Open不显示新消息，需要动一下窗口，就能显示，怀疑这块是一个easyui的bug
	$('#message_windows').window('open');//打开窗口
	$('#message_windows').window('collapse');//折叠
	$('#message_windows').window('expand');//展开
	
}

//修改消息是否查看状态为以查看
function UpdateIsOpen(fromuserid,fromusername){
	$.ajax({
	    type : "get",
	    async:true, //true为异步方法 false为同步方法
	    url : 'UpdateIsOpen?fromuserid='+fromuserid,
	    success : function(data) {
	        if(data.code=='SUCCESS'){
				$('#message_user_'+fromuserid).text(fromusername);
	        }
	    },
	    error: function (data) {
	        parent.alertErrorMessager('ajax错误：'+data);
	    }
	});
}

/**
 * 关闭聊起页
 */
function CloseMessageWindows(touserid,tousername){
	$('#MessageTab').tabs('close', tousername);
	var tab = $('#MessageTab').tabs('getSelected');
	var index = $('#MessageTab').tabs('getTabIndex',tab);
	if(index<0){
		//关闭windows窗口
		$('#message_windows').window('close');
	}
}

/**
 * 菜单事件方法
 */
function MenuTreeSelect(o){
  	addTab(o.text,o.url,o.iconCls);
}

/**
 * 手机端打开菜单方法
 */
function MenuTreeSelectMobile(o){
  	//alert(o.text+o.url+o.iconCls);
  	window.location.href=o.url;
}

/**
 * 创建Tab
 * @param number
 * @param title
 * @param url
 */
function addTab(tab_title,url,iconcls){
	if(url!='#'){
		if(isNotNull(url) && isNotNull(tab_title) && url!='#'){
		    if (!$('#myTab').tabs('exists', tab_title)) {
		        $('#myTab').tabs('add', {
		            title: tab_title,
		            content: '<iframe name="mainFrame" scrolling="auto" frameborder="0"  src="' + url + '" style="width:100%;height:100%;"></iframe>',
		            closable: true,
		            iconCls:iconcls
		        });
		    } else {
		        $('#myTab').tabs('select', tab_title);
		    }
		}else{
			alertErrorMessager("菜单参数缺失，无法打开功能。tab_title："+tab_title+" | URL:"+url+" |iconcls:"+iconcls);
		}
	}
}

/**
 * 提示信息
 */
function alertMessager(msg){
	//提示信息
	$.messager.show({
        title:'信息提示',
        msg:msg,
        timeout:3000,
        showType:'slide'
    });
}

/**
 * 提示信息2
 */
function alertMessager2(msg){
	$('#alert_windows').html(msg);
	$('#alert_windows').window('open');
}

/**
 * 弹出错误提示框
 */
function alertErrorMessager(msg){
	$('#error_windows').html(msg);
	$('#error_windows').window('open');
}

/**
 * 图片展示框
 */
function alertImgWindows(imgUrl){
	$('#img_windows').html("<img style='height:100%;padding: 10px;' src='"+imgUrl+"'>");
	$('#img_windows').window('open');
}

/**
 * 打开加载等待
 */
function openLoading(){
	$('#loading_windows').window('open');
}
/**
 * 关闭加载等待
 */
function closedLoading(){
	$('#loading_windows').window('close');
}

/**
 * 用户设置
 */
function user_settings(){
	addTab("设置","user_settings");
}

/**
 * 打开待办任务页面
 */
function my_workjob_list(){
	addTab("待办任务","rlist?zid=2a3810a816b847o2rp4arzd21a2e125178tfc219731e172317241514163008");
}

/**
 * 更新系统缓存
 */
function LoadParameter(){
	$.ajax({
		type : "GET",
		url : 'LoadParameter',
		success : function(data) {
			if(data.code=='SUCCESS'){
				alertMessager(data.msg);
			}else{
				alertErrorMessager(data.msg);
			}
		}
	});
	
}

/**
 * 设置系统参数
 */
function SetSystemParameter(){
	addTab("设置系统参数","list?tableId=z_sp");
}


//初始化菜单数据
var menuTreeList = jQuery.parseJSON('${menuTreeList}');

/**
 * 重启Tomcat
 */
function RestartTomcat(){
	$.messager.confirm('信息提示','您确定要重启Tomcat服务吗？执行完成后，请等待30秒刷新页面，查看Tomcat服务是否启动',function(r){
		if (r){
			$.ajax({
				type : "GET",
				url : 'RestartTomcat',
				success : function(data) {
					if(data.code=='SUCCESS'){
						window.location.reload();
					}else{
						alertErrorMessager(data.msg);
					}
				},
				timeout:1000,
				error: function(XMLHttpRequest, textStatus, errorThrown){  
					window.location.reload();
			    }  
			});
		}
	});
}

</script>

<style type="text/css">
.msgbox{
margin-bottom: 14px;
}	
.msgboxtext{
margin-left: 20px;
font-size:16px;
white-space: pre;
}

.msgboxhead0{
color:#0000ff;
font-size:14px;
}
.msgboxhead1{
color:#008040;
font-size:14px;
}

#清空树型菜单显示图标
.tree-folder{
  background: none;
}
.tree-folder-open{
  background: none;
}
.tree-file {
  background: none;
}

</style>